package com.zbbt.sportslottery.net;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.net.parser.Result;
import com.zbbt.sportslottery.net.parser.ResultParser;
import com.zbbt.sportslottery.util.DataValidator;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;

/**
 * 
 * @ClassName: TypeGsonHttpHandler
 * @Description: http请求解析
 * @author：LiZhimin
 * @date：2014-12-9 上午10:46:51
 * @version V1.0
 * @param <T>
 */
public abstract class TypeGsonHttpHandler<T> extends RequestCallBack<String> {
	private boolean showToast = false;// 是否显示错误提示

	public TypeGsonHttpHandler() {}

	public TypeGsonHttpHandler(boolean showToast) {
		this.showToast = showToast;
	}

	public abstract void onSuccess(T data);

	public abstract void onFailure(String errorCode, String errorMsg);

	@Override
	public void onSuccess(ResponseInfo<String> responseInfo) {
		if (responseInfo == null)
			return;
		String jsonString = responseInfo.result;
		LogUtil.printI(Constant.HTTP_TAG, jsonString);
		final Object jsonResponse = parseResponse(jsonString);
		Result mResult = null;
		T mData = null;
		if (jsonResponse instanceof JSONObject) {
			JSONObject resultJson = (JSONObject) jsonResponse;
			try {
				mResult = ResultParser.parse(resultJson);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if (mResult != null) {
			if (!TextUtils.isEmpty(mResult.getCode())) {
				if (!mResult.getCode().equals(Constant.SUCCEE_CODE)) {
					if (!TextUtils.isEmpty(mResult.getMsg())) {
						onError(mResult.getCode(), mResult.getMsg());
					}
				} else {
					String resultStr = mResult.getResult();
					if (!TextUtils.isEmpty(resultStr)) {
						final Gson gson = new Gson();
						try {
							LogUtil.printD("ssssaaaaaa", "yes:"+resultStr);
							mData = gson.fromJson(resultStr, getGenericType());
						} catch (Exception e) {
							e.printStackTrace();
							LogUtil.printD("ssssaaaaaa", "no");
							onSuccess(mData);
						}
						onSuccess(mData);
					} else {
						onSuccess(mData);
					}
				}
			}
		}
	}

	@Override
	public void onFailure(HttpException error, String msg) {
		if (DataValidator.isNetError(msg)) {
			msg = "无法连接服务器，请检查网络是否正常";
		}
		onError("9999", msg);
	}

	private void onError(String errorCode, String errorMsg) {
		if (showToast) {
			ToastUtil.showShort(errorMsg);
		}
		onFailure(errorCode, errorMsg);
	}

	public Type getGenericType() {
		Class<?> clazz = this.getClass();
		Type genericSuperclass = clazz.getGenericSuperclass();
		if (genericSuperclass instanceof ParameterizedType) {
			Type[] typeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
			Type type = typeArguments[0];
			return type;
		}
		return null;
	}

	public static Object parseResponse(String jsonString) {
		Object result = null;
		if (jsonString != null) {
			jsonString = jsonString.trim();
			if (jsonString.startsWith("{")) {
				try {
					result = new JSONTokener(jsonString).nextValue();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		if (result == null) {
			result = jsonString;
		}
		return result;
	}
}
